package com.hongxun.budget.utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Point;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.amap.api.maps.model.TextOptions;
import com.hongxun.budget.R;
import com.hongxun.budget.greendao.DCrossCostEntityDao;
import com.hongxun.budget.greendao.DPointEntityDao;
import com.hongxun.budget.greendao.DaoSession;
import com.hongxun.budget.ui.activity.tk.ProjectActivity;
import com.hongxun.budget.ui.activity.tk.SetMainActivity;
import com.hongxun.budget.ui.dialog.MarkerClickDialog;
import com.hongxun.greenentity.tk.DCrossCostEntity;
import com.hongxun.greenentity.tk.DPointEntity;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

/**
 * 作图工具类
 */

public class DrawMapUtils implements AMap.OnMarkerClickListener {
    AMap aMap;
    boolean isVisibleSpan;//是否显示档距
    boolean isVisibleBianhao;//是否显示编号
    String process;//操作方式:选择点位
    DaoSession session;
    Activity context;
    boolean isDragIcon;//是否显示拖拽图标

    String work = "全部";

    /**
     * @param context
     * @param aMap
     * @param isVisibleSpan
     * @param isVisibleBianhao
     * @param process          操作类型，关联点位点击事件(选择点位)
     */
    public DrawMapUtils(Activity context, AMap aMap, boolean isVisibleSpan, boolean isVisibleBianhao, String process) {
        session = GreenDaoManager.getInstance().getmDaoSession();
        this.aMap = aMap;
        this.isVisibleSpan = isVisibleSpan;
        this.isVisibleBianhao = isVisibleBianhao;
        this.process = process;
        this.context = context;
    }

    public void setWork(String work) {
        this.work = work;
    }

    public void setVisibleSpan(boolean visibleSpan) {
        isVisibleSpan = visibleSpan;
    }

    public void setVisibleBianhao(boolean visibleBianhao) {
        isVisibleBianhao = visibleBianhao;
    }

    public void setDragIcon(boolean dragIcon) {
        isDragIcon = dragIcon;
    }

    public void draw() {
        if (aMap == null) aMap = ((ProjectActivity) context).getaMap();
        aMap.clear();
        String guid = (String) SPUtils.get(context, "project_guid", "");//获取项目的GUID
        //获取所有的点位信息，并不包含有关联点的点位信息
        QueryBuilder<DPointEntity> builder = session.getDPointEntityDao().queryBuilder();
        List<DPointEntity> pointEntities = builder.where(DPointEntityDao.Properties.PGuid.eq(guid)
                , DPointEntityDao.Properties.PPWorktype.like(work.equals("全部") ? "%%" : "%" + work + "%")
                , DPointEntityDao.Properties.PPDatastate.notEq("删除")
                , builder.or(DPointEntityDao.Properties.PPParentguid.isNull(), DPointEntityDao.Properties.PPParentguid.eq(""))).list();
        for (DPointEntity d : pointEntities) {//先作线
            if (!TextUtils.isEmpty(d.getPPUpguid())) {
                drawLine(d);
            }
        }
        for (DPointEntity d : pointEntities) {//再做点
            drawMarker(d);
        }
        List<DCrossCostEntity> costEntities = session.getDCrossCostEntityDao().queryBuilder()
                .where(DCrossCostEntityDao.Properties.PGuid.eq(guid), DCrossCostEntityDao.Properties.CCDatastate.notEq("删除")).build().list();
        for (DCrossCostEntity d : costEntities) {//交叉跨越单独绘制
            drawCrossMarker(d);
        }
        if (isDragIcon) {//添加中心定位图标
            addMarkerInScreenCenter();
        }
        aMap.setOnMarkerClickListener(this);
    }


    /**
     * 如果存在上联则需要做导线
     *
     * @param d
     */
    void drawLine(DPointEntity d) {
        DPointEntity preD = session.getDPointEntityDao().load(d.getPPUpguid());//获取上联点位
        List<LatLng> latLngs = new ArrayList<LatLng>();
        latLngs.add(new LatLng(d.getPPInputlatitude(), d.getPPInputlongitude()));
        latLngs.add(new LatLng(preD.getPPInputlatitude(), preD.getPPInputlongitude()));
        aMap.addPolyline(new PolylineOptions().
                addAll(latLngs).width(10).color(Color.argb(255, 1, 1, 1)));
        if (isVisibleSpan) {
            LatLng spanLatlng = new LatLng((latLngs.get(0).latitude + latLngs.get(1).latitude) / 2, (latLngs.get(0).longitude + latLngs.get(1).longitude) / 2);
            TextOptions textOptions = new TextOptions();
            textOptions.fontColor(Color.argb(255, 0, 0, 0));
            textOptions.fontSize(DensityUtil.dip2px(context, 10));
            textOptions.backgroundColor(Color.argb(255, 255, 255, 255));

            textOptions.text(d.getPPInputspan() == null ? "" : (d.getPPInputspan() + ""));
            textOptions.rotate(0);
            textOptions.position(spanLatlng);
            aMap.addText(textOptions);
        }
    }

    void drawCrossMarker(final DCrossCostEntity d) {
        View v = LayoutInflater.from(context).inflate(R.layout.view_drawmap, null);
        TextView code = v.findViewById(R.id.code);//编号
        ImageView icon = v.findViewById(R.id.icon);//图标
        RecyclerView listView = v.findViewById(R.id.list);//子点
        listView.setVisibility(View.GONE);//交叉跨越没有子点
        icon.setImageResource(R.mipmap.p_jcky_show);
        code.setVisibility(View.GONE);//交叉跨越没有编号
        Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng(d.getCCInputlatitude(), d.getCCInputlongitude()))
                .icon(BitmapDescriptorFactory.fromView(v)).anchor(0.5f, 0.5f));
        marker.setObject(d);
    }

    void drawMarker(final DPointEntity d) {
        List<DPointEntity> list = session.getDPointEntityDao().queryBuilder()
                .where(DPointEntityDao.Properties.PPParentguid.eq(d.getGuid())
                        , DPointEntityDao.Properties.PPDatastate.notEq("删除")).build().list();
        View v = LayoutInflater.from(context).inflate(R.layout.view_drawmap, null);
        TextView code = v.findViewById(R.id.code);//编号
        ImageView icon = v.findViewById(R.id.icon);//图标
        RecyclerView listView = v.findViewById(R.id.list);//子点
        ViewUtils.setIcon(d, icon);
        code.setText(d.getPPCode());
        if (isVisibleBianhao) {
            code.setVisibility(View.VISIBLE);
        } else {
            code.setVisibility(View.GONE);
        }
        if (list.size() == 0) listView.setVisibility(View.GONE);
        else {
            listView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context));
            SuperAdapter<DPointEntity> adapter;
            listView.setAdapter(adapter = new SuperAdapter<DPointEntity>(R.layout.content_drawmap) {
                @Override
                public void bindView(ViewHolder viewHolder, final DPointEntity d, int i) {
                    ImageView icon = viewHolder.getView(R.id.icon);
                    TextView code = viewHolder.getView(R.id.code);
                    ViewUtils.setIcon(d, icon);
                    code.setText(d.getPPCode());
                    if (isVisibleBianhao) {
                        code.setVisibility(View.VISIBLE);
                    } else {
                        code.setVisibility(View.GONE);
                    }
                }
            });
            adapter.setData(list);
        }
        Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng(d.getPPInputlatitude(), d.getPPInputlongitude()))
                .icon(BitmapDescriptorFactory.fromView(v)).anchor(0.5f, 0.5f));
        marker.setObject(d);
    }


    @Override
    public boolean onMarkerClick(Marker marker) {
        if (marker.getObject() instanceof DPointEntity) {
            DPointEntity d = (DPointEntity) marker.getObject();
            List<DPointEntity> list = session.getDPointEntityDao().queryBuilder()
                    .where(DPointEntityDao.Properties.PPParentguid.eq(d.getGuid())
                            , DPointEntityDao.Properties.PPDatastate.notEq("删除")).build().list();
            if (list.size() == 0 || process.equals("选择点位"))
                pointClick((DPointEntity) marker.getObject());
            else if (process.equals("查看")) {
                new MarkerClickDialog().setD(d).show(context.getFragmentManager(), "");
            }
        } else if (marker.getObject() instanceof DCrossCostEntity)
            crossClick((DCrossCostEntity) marker.getObject());
        return false;
    }

    void crossClick(DCrossCostEntity d) {
        Intent intent = null;
        switch (process) {
            case "选择点位":
                T.showLong(context, "交叉跨越不能作为关联点或上联点");
                break;
            case "查看":
                intent = new Intent(context, SetMainActivity.class);
                intent.putExtra("point", d);
                context.startActivity(intent);
                break;
        }
    }

    void pointClick(DPointEntity d) {
        Intent intent = null;
        switch (process) {
            case "选择点位":
                intent = new Intent();
                intent.putExtra("point", d);
                context.setResult(Activity.RESULT_OK, intent);
                context.finish();
                break;
            case "查看":
                intent = new Intent(context, SetMainActivity.class);
                intent.putExtra("point", d);
                context.startActivity(intent);
                break;
        }
    }

    public void addMarkerInScreenCenter() {
        LatLng latLng = aMap.getCameraPosition().target;
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        Marker locationMarker = aMap.addMarker(new MarkerOptions()
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.purple_pin)));
        //设置Marker在屏幕上,不跟随地图移动
        locationMarker.setPositionByPixels(screenPosition.x, screenPosition.y);
        locationMarker.setZIndex(1);

    }
}
